#include <QtGui>
#include "measform.h"
#include "meascfgdlg.h"
#include "../core/ctrl.h"
#include "../core/ctrlthread.h"
#include "../core/measprog.h"
#include "../ipcuty.h"

#include "../wrapper.h"

MeasForm::MeasForm(QWidget *parent)
    :QMdiSubWindow(parent)
{
	ui.setupUi(this);
//    btnSetting   = new QPushButton(tr("OPTIONS"));
//    btnStartMeas = new QPushButton(tr("START"));
//	btnStop		 = new QPushButton(tr("STOP"));
	btnSetting   = ui.settingButton;
	btnStartMeas = ui.startButton;
	btnStop      = ui.backButton;
	btnManual	 = ui.displayButton;
//	btnManual    = new QPushButton(tr("MANUAL"));
	btnManual->setVisible(false);

//    tableProgData = new QTableWidget(TABLE_PROGDATA_ROWS, TABLE_PROGDATA_COLS);
	tableProgData = ui.totalTable;
	tableItemData = ui.itemTable;

	tableProgData->setRowCount(TABLE_PROGDATA_ROWS);
	tableProgData->setColumnCount(TABLE_PROGDATA_COLS);
    tableProgData->verticalHeader()->setVisible(false);
    tableProgData->horizontalHeader()->setVisible(false);
    QStringList strListProgDataHeader;
    strListProgDataHeader << tr("GO") << tr("NG") << tr("TOTAL");
//    for(int c = 0; c < TABLE_PROGDATA_COLS; ++c){
//        tableProgData->setHorizontalHeaderItem(c,
//                             new QTableWidgetItem(strListProgDataHeader.at(c)));
//        tableProgData->setColumnWidth(c, 150);
//    }
 //   tableProgData->setFixedSize(455, 60);

//    tableProgData->setCellWidget(0, 0, new QLabel(tr("0")));
//    tableProgData->setCellWidget(0, 1, new QLabel(tr("0")));
//    tableProgData->setCellWidget(0, 2, new QLabel(tr("0")));


//    for(int c = 0; c < TABLE_PROGDATA_COLS; ++c){
//        QLabel *label = qobject_cast<QLabel *>(tableProgData->cellWidget(0, c));
//        label->setAlignment(Qt::AlignCenter);
//    }
//	QLabel *prog_label = NULL;
	QTableWidgetItem *prog_label = NULL;
	QBrush brush(QColor(99, 99, 99));
	for(int r = 0; r < TABLE_PROGDATA_ROWS; ++r){
		if(r%2 == 0){
			prog_label = new QTableWidgetItem(strListProgDataHeader.at(r/2));
			prog_label->setBackground(brush);
		}else{
			prog_label = new QTableWidgetItem(tr("0"));
		}
		prog_label->setTextAlignment(Qt::AlignCenter);
		tableProgData->setItem(r, 0, prog_label);
		tableProgData->setRowHeight(r, 70);
	}
	tableProgData->setColumnWidth(0, 120);

/*
    QHBoxLayout *hlayoutProgData = new QHBoxLayout;
    hlayoutProgData->addWidget(tableProgData);
    hlayoutProgData->addStretch();
    hlayoutProgData->addWidget(btnSetting);
    hlayoutProgData->addWidget(btnStartMeas);
	hlayoutProgData->addWidget(btnStop);
	hlayoutProgData->addWidget(btnManual);
*/

//    tableItemData = new QTableWidget(TABLE_ITEMDATA_ROWS, TABLE_ITEMDATA_COLS);
	tableItemData->setRowCount(TABLE_ITEMDATA_ROWS);
	tableItemData->setColumnCount(TABLE_ITEMDATA_COLS);
    QStringList strListItemDataHeader;
    strListItemDataHeader << tr("ITEM NAME") << tr("ITEM NG")
                                << tr("JUDGE") << tr("A/D VALUE") << tr("MEAS VALUE");
    for(int c = 0; c < TABLE_ITEMDATA_COLS; ++c){
        tableItemData->setHorizontalHeaderItem(c,
                             new QTableWidgetItem(strListItemDataHeader.at(c)));
        tableItemData->setColumnWidth(c, 115);
    }
	
	QLabel *label;
	for(int r = 0; r < TABLE_ITEMDATA_ROWS; ++r){
		for(int c = 0; c < TABLE_ITEMDATA_COLS; ++c){
			label = new QLabel();
			label->setAlignment(Qt::AlignCenter);
			tableItemData->setCellWidget(r, c, label);
		}
	}	

/*
    QVBoxLayout *vlayoutMeas = new QVBoxLayout;
    vlayoutMeas->addLayout(hlayoutProgData);
    vlayoutMeas->addWidget(tableItemData);

    QFrame *frame = new QFrame;
    frame->setLayout(vlayoutMeas);

    setWidget(frame);
*/
	// set font size
	QFont font = this->font();
	font.setPixelSize(font.pointSize() * 4 / 3);
	setFont(font);

    setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    showMaximized();

	connect(btnStartMeas, SIGNAL(clicked()), this, SLOT(startMeas()));
	connect(btnStop, SIGNAL(clicked()), this, SLOT(stopMeas()));
	connect(btnSetting, SIGNAL(clicked()), this, SLOT(openMeasCfgDlg()));
	connect(btnManual, SIGNAL(clicked()), this, SLOT(manualClicked()));
	
//	qDebug() << "measform construct finished!!!!!!!!!!!!!!!!!!!!!!!";
}

void MeasForm::showMeasData()
{
//	qDebug() << "signal catched!!!!!!!!!!!!!";
//	Ctrl* pCtrl = Ctrl::getInstance();
//	result_s *data = pCtrl->getDataShmPtr();
	sem_p(semid);

	total_s* total = getTotalDataPtr();
	measure_s* meas_tmp = getMeasDataPtr();
	
//	QLabel *label;

	// prog data
//	label = qobject_cast<QLabel *>(tableProgData->cellWidget(0, 0));
//	label->setText(QString::number(total->totalgo));
//	label = qobject_cast<QLabel *>(tableProgData->cellWidget(0, 1));
//	label->setText(QString::number(total->totalng));
//	label = qobject_cast<QLabel *>(tableProgData->cellWidget(0, 2));
//	label->setText(QString::number(total->total));
	tableProgData->item(1, 0)->setText(QString::number(total->totalgo));
	tableProgData->item(3, 0)->setText(QString::number(total->totalng));
	tableProgData->item(5, 0)->setText(QString::number(total->total));


	// chip No. 写入
	out_put << total->total; //<< std::endl;	

	MeasProg *mp = MeasProg::getInstance();
	program_s *pp = mp->getProgPtr();
//	item_s *item = NULL;

	ushort range_code = 0;
	const rng_tbl_s *range = NULL;

	QLabel *label;
	QString itemName;
	double mvalue = 0.0;
	QString strData;
	int point_pos	= -1;
	int decimal_len = 0;
	// item data
	for(int itemIndex = 0; itemIndex < 25; ++itemIndex){
		// should not display inactive ones
		if(meas_tmp->item[itemIndex].active != 42){
			continue;
		}

		// item name
		label = qobject_cast<QLabel *>(tableItemData->cellWidget(itemIndex, 0));
		AprCfg::getParamNameByCode(meas_tmp->item[itemIndex].code, itemName);
		label->setText(itemName);

		// item go
		label = qobject_cast<QLabel *>(tableItemData->cellWidget(itemIndex, 1));
		label->setText(QString::number(meas_tmp->go));
	
		// judge
		label = qobject_cast<QLabel *>(tableItemData->cellWidget(itemIndex, 2));
		label->setText(71 == meas_tmp->item[itemIndex].judge ? "GO" : "NG");

		// meas data
		label = qobject_cast<QLabel *>(tableItemData->cellWidget(itemIndex, 3));
//		label->setText(QString::number(meas_tmp->item[itemIndex].mvalue));	

		// show A/D value for now ==============================================
		range_code = pp->kinds[0].item[itemIndex].mrange;
		//range = AprCfg::getRangeByCode(range_code);
		//mvalue = meas_tmp->item[itemIndex].mvalue * range->step;
		//strData = QString::number(mvalue) + range->unit;
		//label->setText(strData);
		label->setText(QString::number(meas_tmp->item[itemIndex].mval));


		label = qobject_cast<QLabel *>(tableItemData->cellWidget(itemIndex, 4));
		range = AprCfg::getRangeByCode(range_code);
		mvalue = meas_tmp->item[itemIndex].mvalue * range->step;
		qDebug() << "=========" << range->step;
//		strData = QString::number(mvalue);
//		strData = QString::number(mvalue) + tr(" ") + range->unit;
		strData = QString::number(meas_tmp->item[itemIndex].mval / 32768.0 * 10.0);
//		point_pos = strData.indexOf(tr("."));
//		if(point_pos != -1){
//			decimal_len = strData.length() - point_pos - 1;
//		}else{
//			strData += tr(".");
//			decimal_len = 0;
//		}
//		for(int i = 0; i < 5 - decimal_len; ++i){
//			strData += tr("0");
//		}
//		if(decimal_len > 5){
//			strData = strData.left(strData.length() - (decimal_len - 5));
//		}
		strData = strData + tr(" ") + range->unit;
		
		label->setText(strData);


/*
		qDebug() << data->mdata.item[itemIndex].mrng->step;	
		mvalue = (data->mdata.item[itemIndex].mvalue) * (data->mdata.item[itemIndex].mrng->step);
		strData = QString::number(mvalue) + ' ' + data->mdata.item[itemIndex].mrng->unit;
		label->setText(strData);
*/

		// 每项目的项目名，测试数据，判定结果写入
		//out_put << ',' << itemName.toStdString() << ',' << meas_tmp->item[itemIndex].mval << ',' << meas_tmp->item[itemIndex].judge;// << ',' << mvalue ;
		out_put << ',' << itemName.toStdString() << ',' << mvalue << ',' << range->unit << ',' << meas_tmp->item[itemIndex].judge;// << ',' << mvalue ;
	}	
	out_put << std::endl;

	sem_v(semid);
}

void MeasForm::startMeas()
{
	if(checkMaster()){	// 需要先进行master测试
		return;
	}

	MeasProg* pm = MeasProg::getInstance();
	program_s* p = pm->getProgPtr();
	if(PM_MANUAL == p->mmode){
		btnManual->setVisible(true);
	}

	// 通常测试
	pm->setMeasType(TYPE_NORMEAS);


	//
	// 写入数据文件头
	//
	QString filePath = pm->getProgFilePath();
	filePath = filePath.left(filePath.indexOf('.'));
	filePath += "_data.csv";
	out_put.open(filePath.toStdString().c_str(), std::ofstream::out | std::ofstream::trunc);
	std::string itemTitle = ", Item Name., Meas. Value, Unit, Judge";
	std::string itemTag = ", , Item";
	out_put << "Chip No.";
	for(int i = 0; i < p->item_total; ++i){
		out_put << itemTag << i+1;
	}
	out_put << std::endl;

	for(int i = 0; i < p->item_total; ++i){
		out_put << itemTitle;
	}
	out_put << std::endl;
//	out_put << "Chip No." << itemTitle << itemTitle << itemTitle << std::endl;  

	Ctrl* pCtrl = Ctrl::getInstance();
	pCtrl->cpyProgramToShm();
//	pCtrl->setMeasState(true);
	semid = sem_create_u();

	pCtrl->startCtrlThread();
}

void MeasForm::stopMeas()
{
	Ctrl* pCtrl = Ctrl::getInstance();
	CtrlThread* thread = pCtrl->getCtrlThread();
	thread->setMeasStatus(false);
//	pCtrl->setMeasState(false);
	btnManual->setVisible(false);

	// 关闭数据文件
	out_put.close();


	delete this;
}


void MeasForm::openMeasCfgDlg()
{
	MeasCfgDlg* dlg = new MeasCfgDlg(this);
	dlg->exec();
	delete dlg;
}

//
// 检查是否需要先进行master测试
//
bool MeasForm::checkMaster()
{
	bool bMaster = false;


	MeasProg* pMeasProg = MeasProg::getInstance();
	program_s* p = pMeasProg->getProgPtr();

	QStringList items;
	citem_t citem;
	usechn_t usechn;
	chnitem_t chnitem;
	if(AprCfg::getHueItemsList(*p, items, citem, usechn, chnitem) == false){
		return bMaster;
	}

	qDebug() << "chnitem =====================";
	qDebug() << chnitem[0];

	for(int i = 0; i < 3; ++i){
		qDebug() << usechn[i];
	}

	for(int ch = 0; ch < MAX_CHANNEL_QTY; ++ch){
//		if((true == usechn[ch]) && (INVALID == p->kinds[0].hue_cfg[ch].active)){
			// 只有在存在该通道的未校准光量项目时,才需要进行master测试,NOTE!:待验证
//			bMaster = true;
//			break;
//		}
		if(true == usechn[ch]){
			if(((chnitem[ch] & MST_HUE) != 0) && (INVALID == p->kinds[0].hue_cfg[ch].active)){
				bMaster = true;
				break;
			}
			if(((chnitem[ch] & MST_VL) != 0) && (INVALID == p->kinds[0].vl_cfg[ch].active)){
				bMaster = true;
				break;
			}
			if(((chnitem[ch] & MST_DLM) != 0) && (INVALID == p->kinds[0].dlm_cfg[ch].active)){
				bMaster = true;
				break;
			}
		}
	}

	if(bMaster){
		QMessageBox::information(this, tr("INFORMATION"), tr("MASTER MEAS NEEDED!"));
	}

	return bMaster;
}


void MeasForm::manualClicked()
{
	//emit manualTriggered();	
	Ctrl* pCtrl = Ctrl::getInstance();
	CtrlThread* thread = pCtrl->getCtrlThread();

	thread->setManual();
}
